const crypto = require("crypto");

function encryptUrl(originalUrl, secretKey) {
	const urlParts = originalUrl.split("/");
	const lastPart = urlParts[urlParts.length - 1];
	const [fileId, fileExt] = lastPart.split('.');

	const isNumericId = /^\+?[1-9][0-9]*$/.test(fileId);
	const isJhtmlFile = fileExt.includes("jhtml");

	if (isNumericId && isJhtmlFile) {
		// 使用 AES-ECB 加密（Node.js 的 crypto 默认使用 PKCS7 填充）
		const cipher = crypto.createCipheriv(
			"aes-128-ecb",
			Buffer.from(secretKey), // 密钥必须是 16/24/32 字节长度
			null // ECB 模式不需要 IV
		);

		let encrypted = cipher.update(fileId, "utf8", "base64");
		encrypted += cipher.final("base64");

		// 替换特殊字符并去除末尾的 =
		encrypted = encrypted.replace(/\//g, "^").replace(/=+$/, "");

		urlParts[urlParts.length - 1] = `${encrypted}.${fileExt}`;
		return urlParts.join("/");
	}
	return originalUrl;
}
